﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Script.Serialization;
using System.Threading;
using log4net;

namespace FlyComet
{
    public class FlyCometHandler : IHttpAsyncHandler
    {
        private static readonly ILog log = LogManager.GetLogger(typeof(FlyCometHandler).Name);
        public bool IsReusable
        {
            get { return false; }
        }

        public IAsyncResult BeginProcessRequest(HttpContext ctx,
                                                AsyncCallback cb,
                                                object obj)
        {
            String cmd = ctx.Request["command"];
            log.Info(String.Format("Received async request {0})", ctx.Request.RawUrl));

            if (!String.IsNullOrEmpty(cmd))
                cmd = cmd.ToLower();
            else
            {
                LiveMessage fsqmsg = new LiveMessage() { StatusCode = -1, StatusDescription = "FlyCometHandler: Invalid command received", Message = "" };
                JavaScriptSerializer js = new JavaScriptSerializer();
                string Serilizeddata = js.Serialize(fsqmsg);

                ctx.Response.Output.WriteLine(Serilizeddata);
                ctx.Response.StatusCode = 200;
                ctx.Response.End();
                return null;
            }

            AsyncRequestState reqState = new AsyncRequestState(ctx, cb, obj);
            AsyncRequest ar = new AsyncRequest(reqState);
            ThreadStart ts = new ThreadStart(ar.ProcessRequest);
            Thread t = new Thread(ts);
            t.Start();

            return reqState;
        }

        public void EndProcessRequest(IAsyncResult ar)
        {
            // This will be called on the manually created thread in response to 
            // calling the ASP.NET AsyncCallback delegate once the request has
            // completed processing. The incoming IAsyncResult parameter will be 
            // a reference to the AsyncRequestState class, so the Context can be
            // accessed through that class. Note - you *cannot* access the 
            // current context using the HttpContext.Current property, as you are 
            // running on your own thread which has not been initialized with a 
            // context reference.
            AsyncRequestState ars = ar as AsyncRequestState;
            if (ars != null)
            {
                // here you could perform some cleanup, write something else to the
                // Response, or whatever else you need to do
            }
        }

        #region IHttpHandler Members


        public void ProcessRequest(HttpContext context)
        {
        }

        #endregion
    }
}